const { Service } = require("egg");
class CategoryService extends Service {
  async addCategory(categoryName, icon) {
    const { ctx } = this;
    const db = ctx.model.Category;
    const findItem = await db.findOne({ categoryName });
    if (findItem) {
      return { msg: "类目不能重复", success: false, code: 409 };
    } else {
      const res = await db.create({ categoryName, icon });
      return { msg: "成功", data: res };
    }
  }
  // 获取分类，连表查询分类下的商品数量
  async getCategory(page = 1, size = 15) {
    const { ctx } = this;
    const db = ctx.model.Category;
    const res = await db.aggregate([
      { $skip: Number((page - 1) * size) },
      { $limit: Number(size) },
      {
        // 连表查询
        $lookup: {
          // 每一个loopup查询结果都是一个数组
          from: "Goods", //要连接的表
          localField: "_id",
          foreignField: "categoryId",
          as: "quantity", //自定义的输出字段，该字段包含了Goods集合的所有文档
        },
      },
      {
        $project: {
          _id: 1,
          categoryName: 1,
          icon: 1,
          quantity: { $size: "$quantity" }, //$size：获取quantity这个字段数组的长度
        },
      },
    ]);
    const total = await db.countDocuments();
    return {
      data: { list: res, total, page, size },
    };
  }
  //   获取分类及对应下的商品
  async getCategoryGoods() {
    const { ctx } = this;
    const res = await ctx.model.Category.aggregate([
      {
        $lookup: {
          from: "Goods",
          localField: "_id",
          foreignField: "categoryId",
          as: "goodsList",
        },
      },
      {
        $match: {
          goodsList: { $ne: [] }, //匹配goodsList不为空的分类
        },
      },
      {
        $project: {
          createdAt: 0,
          updatedAt: 0,
          "goodsList.createdAt": 0,
          "goodsList.updatedAt": 0,
        },
      },
    ]);
    return {
      data: res,
      msg: "成功",
    };
  }
}
module.exports = CategoryService;
